<script setup>
import { ref, onMounted } from "vue";
import {
  getJobTypeTopListApi,
  getJobTypeChildrenListApi,
} from "@/api/jobType.js";

// 页面参数
const props = defineProps({
  title: {
    type: String,
    default: "选择行业类别",
  },
});

// 数据状态
const firstLevelList = ref([]); // 一级分类列表
const loadingStates = ref({}); // 加载状态管理
const globalLoading = ref(false); // 全局加载状态

// 选中状态
const selectedFirst = ref(null); // 选中的一级分类
const selectedSecond = ref(null); // 选中的二级分类
const selectedThird = ref(null); // 选中的三级分类

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 获取一级分类列表
const getFirstLevelList = async () => {
  try {
    globalLoading.value = true;
    const data = await getJobTypeTopListApi();
    firstLevelList.value = (data || []).map((item) => ({
      ...item,
      children: [], // 初始化为空数组
      childrenLoaded: false, // 标记是否已加载子级数据
    }));

    // 默认选中第一个一级分类
    if (firstLevelList.value.length > 0) {
      await selectFirstLevel(firstLevelList.value[0]);
    }
  } catch (error) {
    console.error("获取一级分类失败:", error);
    uni.showToast({
      title: "获取分类数据失败",
      icon: "none",
    });
  } finally {
    globalLoading.value = false;
  }
};

// 加载二级分类数据
const loadSecondLevelData = async (firstLevelItem) => {
  if (firstLevelItem.childrenLoaded) {
    return; // 已经加载过，直接返回
  }

  const loadingKey = `second_${firstLevelItem.id}`;

  try {
    loadingStates.value[loadingKey] = true;

    const secondLevelData = await getJobTypeChildrenListApi(firstLevelItem.id);

    // 更新一级分类的子级数据
    const targetIndex = firstLevelList.value.findIndex(
      (item) => item.id === firstLevelItem.id
    );
    if (targetIndex !== -1) {
      firstLevelList.value[targetIndex] = {
        ...firstLevelItem,
        children: (secondLevelData || []).map((item) => ({
          ...item,
          children: [], // 初始化三级数据
          childrenLoaded: false, // 标记是否已加载三级数据
        })),
        childrenLoaded: true,
      };

      // 更新选中的一级分类引用
      if (selectedFirst.value && selectedFirst.value.id === firstLevelItem.id) {
        selectedFirst.value = firstLevelList.value[targetIndex];
      }
    }
  } catch (error) {
    console.error(`获取二级分类失败 (${firstLevelItem.id}):`, error);
    uni.showToast({
      title: "获取二级分类失败",
      icon: "none",
    });
  } finally {
    delete loadingStates.value[loadingKey];
  }
};

// 加载三级分类数据
const loadThirdLevelData = async (secondLevelItem) => {
  if (secondLevelItem.isLeaf || secondLevelItem.childrenLoaded) {
    return; // 叶子节点或已经加载过，直接返回
  }

  const loadingKey = `third_${secondLevelItem.id}`;

  try {
    loadingStates.value[loadingKey] = true;

    const thirdLevelData = await getJobTypeChildrenListApi(secondLevelItem.id);

    // 更新二级分类的子级数据
    if (selectedFirst.value && selectedFirst.value.children) {
      const targetIndex = selectedFirst.value.children.findIndex(
        (item) => item.id === secondLevelItem.id
      );

      if (targetIndex !== -1) {
        // 使用Vue的响应式更新
        selectedFirst.value.children[targetIndex] = {
          ...selectedFirst.value.children[targetIndex],
          children: thirdLevelData || [],
          childrenLoaded: true,
        };
      }
    }
  } catch (error) {
    console.error(`获取三级分类失败 (${secondLevelItem.id}):`, error);
    uni.showToast({
      title: "获取三级分类失败",
      icon: "none",
    });
  } finally {
    delete loadingStates.value[loadingKey];
  }
};

// 选择一级分类
const selectFirstLevel = async (item) => {
  selectedFirst.value = item;
  selectedSecond.value = null;
  selectedThird.value = null;

  // 加载二级分类数据
  await loadSecondLevelData(item);
};

// 选择二级分类
const selectSecondLevel = (item) => {
  selectedSecond.value = item;
  selectedThird.value = null;
};

// 处理折叠面板展开事件
const handleCollapseChange = async (e, secondLevelItem) => {
  // 当面板展开时才加载数据
  if (
    e &&
    e.show &&
    !secondLevelItem.isLeaf &&
    !secondLevelItem.childrenLoaded
  ) {
    await loadThirdLevelData(secondLevelItem);
  }
};

// 点击二级分类标题时的处理
const handleSecondLevelClick = async (secondLevelItem) => {
  // 如果不是叶子节点且未加载三级数据，则加载
  if (!secondLevelItem.isLeaf && !secondLevelItem.childrenLoaded) {
    await loadThirdLevelData(secondLevelItem);
  }
};

// 选择三级分类
const selectThirdLevel = (thirdItem, secondItem) => {
  selectedThird.value = thirdItem;
  selectedSecond.value = secondItem;
};

// 获取加载状态
const isLoading = (key) => {
  return loadingStates.value[key] || false;
};

// 保存选择
const saveSelection = () => {
  let selectedData = null;

  // 根据选择层级确定最终选择的数据
  if (selectedThird.value) {
    // 添加检查确保所有必要的值都存在
    if (!selectedFirst.value || !selectedSecond.value) {
      uni.showToast({
        title: "请选择完整的分类",
        icon: "none",
      });
      return;
    }

    selectedData = {
      id: selectedThird.value.id,
      name: selectedThird.value.name,
      level: 3,
      fullPath: `${selectedFirst.value.name} > ${selectedSecond.value.name} > ${selectedThird.value.name}`,
    };
  } else if (selectedSecond.value && selectedSecond.value.isLeaf) {
    // 添加检查确保所有必要的值都存在
    if (!selectedFirst.value) {
      uni.showToast({
        title: "请选择完整的分类",
        icon: "none",
      });
      return;
    }

    selectedData = {
      id: selectedSecond.value.id,
      name: selectedSecond.value.name,
      level: 2,
      fullPath: `${selectedFirst.value.name} > ${selectedSecond.value.name}`,
    };
  } else {
    uni.showToast({
      title: "请选择完整的分类",
      icon: "none",
    });
    return;
  }

  // 返回上一页并传递数据
  const pages = getCurrentPages();
  if (pages.length > 1) {
    const prevPage = pages[pages.length - 2];

    // 方法1：通过页面实例直接调用方法
    if (prevPage && prevPage.$vm && prevPage.$vm.updateFieldValue) {
      prevPage.$vm.updateFieldValue("jobType", selectedData.name);
      prevPage.$vm.updateFieldValue("jobTypeId", selectedData.id);
    }

    // 方法2：通过全局事件总线传递数据（备用方案）
    uni.$emit("updateJobType", selectedData);
  }

  // 将选择的数据存储到本地存储，供上一页面使用
  uni.setStorageSync("selectedJobType", selectedData);

  uni.showToast({
    title: "保存成功",
    duration: 1500,
    success() {
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    },
  });
};

// 重置选择
const resetSelection = () => {
  // 清空选中状态
  selectedFirst.value = null;
  selectedSecond.value = null;
  selectedThird.value = null;

  // 清空本地存储中的选中职位类别
  uni.removeStorageSync("selectedJobType");

  // 返回上一页，传递空值
  const pages = getCurrentPages();
  if (pages.length > 1) {
    const prevPage = pages[pages.length - 2];

    // 通过全局事件总线传递空值数据（备用方案）
    uni.$emit("updateJobType", null);
  }

  uni.navigateBack();
};

// 页面加载
onMounted(() => {
  // 获取当前选中的职位类别（如果有的话）
  const currentJobType = uni.getStorageSync("currentJobType");
  if (currentJobType) {
    console.log("当前职位类别:", currentJobType);
    // 这里可以根据需要预选中相应的分类
    // 由于职位类别选择较复杂，暂时只记录日志
  }

  getFirstLevelList();
});
</script>

<template>
  <view class="job-type-selector">
    <!-- 页头 -->
    <view class="header">
      <view class="header-content">
        <view class="back-btn" @click="goBack">
          <image
            class="back-icon"
            src="/static/icons/candidate/pre_page.png"
          ></image>
        </view>
        <view class="header-title">选择行业类别</view>
        <view class="header-actions">
          <view class="reset-btn" @click="resetSelection">
            <text class="reset-text">重置</text>
          </view>
          <view class="save-btn" @click="saveSelection">
            <text class="save-text">保存</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content">
      <view class="selector-container">
        <!-- 左侧一级分类 -->
        <view class="left-panel">
          <scroll-view scroll-y class="category-list">
            <view
              v-for="item in firstLevelList"
              :key="item.id"
              class="category-item"
              :class="{ active: selectedFirst && selectedFirst.id === item.id }"
              @click="selectFirstLevel(item)"
            >
              <text class="category-name">{{ item.name }}</text>
            </view>
          </scroll-view>
        </view>

        <!-- 右侧二级和三级分类 -->
        <view class="right-panel">
          <scroll-view scroll-y class="category-list">
            <!-- 加载中状态 -->
            <view
              v-if="isLoading(`second_${selectedFirst?.id}`)"
              class="loading-panel"
            >
              <text class="loading-text">加载中...</text>
            </view>

            <!-- 二级分类使用uni-collapse组件 -->
            <view
              v-else-if="
                selectedFirst &&
                selectedFirst.children &&
                selectedFirst.children.length > 0
              "
            >
              <uni-collapse>
                <uni-collapse-item
                  v-for="secondItem in selectedFirst.children"
                  :key="secondItem.id"
                  :title="secondItem.name"
                  :disabled="false"
                  @change="(e) => handleCollapseChange(e, secondItem)"
                  @click="handleSecondLevelClick(secondItem)"
                >
                  <!-- 如果是叶子节点，直接选中 -->
                  <view v-if="secondItem.isLeaf">
                    <view
                      class="leaf-item"
                      :class="{
                        active:
                          selectedSecond && selectedSecond.id === secondItem.id,
                      }"
                      @click="selectSecondLevel(secondItem)"
                    >
                      <text class="leaf-text">选择此分类</text>
                    </view>
                  </view>

                  <!-- 如果有三级分类 -->
                  <view v-else>
                    <!-- 检查是否需要加载三级数据 -->
                    <view
                      v-if="!secondItem.childrenLoaded"
                      class="load-trigger"
                      @click="loadThirdLevelData(secondItem)"
                    >
                      <text class="load-text">点击加载三级分类</text>
                    </view>

                    <!-- 三级分类加载中 -->
                    <view
                      v-else-if="isLoading(`third_${secondItem.id}`)"
                      class="third-loading"
                    >
                      <text class="loading-text">加载三级分类...</text>
                    </view>

                    <!-- 显示三级标签 -->
                    <view
                      v-else-if="
                        secondItem.children && secondItem.children.length > 0
                      "
                    >
                      <view class="tags-container">
                        <view
                          v-for="thirdItem in secondItem.children"
                          :key="thirdItem.id"
                          class="tag-item"
                          :class="{
                            active:
                              selectedThird &&
                              selectedThird.id === thirdItem.id,
                          }"
                          @click="selectThirdLevel(thirdItem, secondItem)"
                        >
                          <text class="tag-text">{{ thirdItem.name }}</text>
                        </view>
                      </view>
                    </view>

                    <!-- 暂无三级分类提示 -->
                    <view
                      v-else-if="secondItem.childrenLoaded"
                      class="empty-tip"
                    >
                      <text class="tip-text">暂无三级分类</text>
                    </view>
                  </view>
                </uni-collapse-item>
              </uni-collapse>
            </view>

            <!-- 暂无二级分类提示 -->
            <view
              v-else-if="selectedFirst && selectedFirst.childrenLoaded"
              class="empty-panel"
            >
              <text class="empty-text">暂无二级分类</text>
            </view>
          </scroll-view>
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-if="globalLoading" class="loading-container">
        <text class="loading-text">加载中...</text>
      </view>
    </view>
  </view>
</template>

<style scoped lang="less">
.job-type-selector {
  background-color: #ffffff;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 页头样式 */
.header {
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  height: 88rpx;
  padding-top: calc(20rpx + var(--status-bar-height, 0));
  position: relative;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 48rpx;
  height: 48rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333333;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.reset-btn {
  width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.reset-text {
  font-size: 32rpx;
  color: #999999;
  font-weight: 500;
}

.save-btn {
  width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.save-text {
  font-size: 32rpx;
  color: #00bdb4;
  font-weight: 500;
}

/* 内容区域 */
.content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.selector-container {
  flex: 1;
  display: flex;
  flex-direction: row;
}

/* 左侧面板 */
.left-panel {
  width: 240rpx;
  background-color: #f8f9fa;
  border-right: 1px solid #e9ecef;
}

.category-list {
  height: calc(100vh - 108rpx);
}

.category-item {
  padding: 30rpx 20rpx;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #ffffff;

  &.active {
    background-color: #f0fffe;
    border-left: 4rpx solid #00bdb4;
  }
}

.category-name {
  font-size: 28rpx;
  color: #333333;
  flex: 1;
}

.arrow-icon {
  width: 24rpx;
  height: 24rpx;
}

/* 右侧面板 */
.right-panel {
  flex: 1;
  background-color: #ffffff;
}

/* 叶子节点样式 */
.leaf-item {
  padding: 24rpx 30rpx;
  border-bottom: 1px solid #f0f0f0;
  background-color: #f8f9fa;
  margin: 10rpx 20rpx;
  border-radius: 8rpx;
  text-align: center;

  &.active {
    background-color: #00bdb4;

    .leaf-text {
      color: #ffffff;
    }
  }
}

.leaf-text {
  font-size: 28rpx;
  color: #333333;
}

/* 标签样式 */
.tags-container {
  padding: 20rpx 30rpx;
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.tag-item {
  padding: 16rpx 24rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  border: 1px solid #e9ecef;

  &.active {
    background-color: #00bdb4;
    border-color: #00bdb4;

    .tag-text {
      color: #ffffff;
    }
  }
}

.tag-text {
  font-size: 28rpx;
  color: #333333;
}

/* 加载触发器 */
.load-trigger {
  padding: 24rpx 30rpx;
  background-color: #f8f9fa;
  margin: 10rpx 20rpx;
  border-radius: 8rpx;
  text-align: center;
  border: 1rpx dashed #00bdb4;

  &:active {
    background-color: #e9ecef;
  }
}

.load-text {
  font-size: 28rpx;
  color: #00bdb4;
}

/* 加载状态 */
.loading-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.loading-panel {
  padding: 60rpx 30rpx;
  text-align: center;
}

.third-loading {
  padding: 30rpx;
  text-align: center;
  background-color: #f8f9fa;
  margin: 10rpx 20rpx;
  border-radius: 8rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #666666;
}

/* 空状态 */
.empty-panel {
  padding: 100rpx 30rpx;
  text-align: center;
}

.empty-tip {
  padding: 30rpx;
  text-align: center;
  background-color: #f8f9fa;
  margin: 10rpx 20rpx;
  border-radius: 8rpx;
}

.empty-text,
.tip-text {
  font-size: 28rpx;
  color: #999999;
}
</style>